package com.atom.module.mvvm.extren

import android.os.Build
import android.widget.AdapterView
import android.widget.AutoCompleteTextView
import androidx.annotation.CheckResult
import androidx.annotation.RequiresApi
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun AutoCompleteTextView.dismisses() = callbackFlow<Unit> {
    checkMainThread()
    val listener = AutoCompleteTextView.OnDismissListener {
        trySend(Unit)
    }
    setOnDismissListener(listener)
    awaitClose { setOnDismissListener(null) }
}.conflate()


@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun AutoCompleteTextView.itemClickEvents() = callbackFlow<AdapterViewItemClickEvent> {
    checkMainThread()
    val listener = AdapterView.OnItemClickListener { parent, view, position, id ->
        trySend(
            AdapterViewItemClickEvent(
                view = parent,
                clickedView = view,
                position = position,
                id = id
            )
        )
    }
    onItemClickListener = listener
    awaitClose { onItemClickListener = null }
}.conflate()
